<template>
  <div class="app-container">
    <el-row style="margin-bottom: 20px">
      <el-col :span="18">
        <el-radio-group size="small" v-model="queryParams.merchantStatus">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="YES">已开启</el-radio-button>
          <el-radio-button label="NO">已停用</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="6" style="display: flex; justify-content: flex-end">
        <el-button type="primary" size="small" @click="handleCreate"
          >新建发包商</el-button
        >
      </el-col>
    </el-row>
    <TheTable
      ref="tableRefs"
      :tableOption="tableOption"
      :pageNo.sync="pageNo"
      :limit.sync="limit"
      :api="queryPageApi"
      :queryParams="queryParams"
    />
    <TheEditForm
      ref="theFormCreate"
      :title="mode == 'create' ? '新建发包商' : '编辑发包商'"
      :api="apiMerchantDetail"
      :mode="mode"
      :options="formOptions"
      :form.sync="ruleForm"
      @submit="handleSubmit"
    >
      <!-- <template v-slot:stockLibraryCode="{ slotProps }">
        <el-select
          :disabled="mode == 'view'"
          :placeholder="slotProps.placeholder"
          v-model="ruleForm[slotProps.field]"
        >
          <el-option ></el-option>
        </el-select>
      </template> -->
      <template v-slot:adminUserName="{ slotProps }">
        <el-input
          :disabled="mode == 'edit'"
          :maxlength="slotProps.maxlength"
          :placeholder="slotProps.placeholder"
          v-model="ruleForm[slotProps.field]"
        ></el-input>
        <el-link v-if="mode == 'edit'" type="primary" @click="handleEditMobile"
          >改绑手机号</el-link
        >
      </template>
    </TheEditForm>
  </div>
</template>
<script>
import {
  apiMerchantPage,
  apiMerchantCreate,
  apiMerchantUpdate,
  apiMerchantDetail,
  apiMerchantUpdateStatus,
} from "@/api/storeManager.js";
import { validateRealName, validatePhone } from "@/utils/validate.js";
import { filterMerchantStatusEnum } from "@/filters";
import TheEditForm from "@/components/TheCreateForm";
export default {
  components: { TheEditForm },
  data() {
    const _this = this;
    return {
      queryPageApi: apiMerchantPage,
      pageNo: 1,
      limit: 10,
      exportLoading: false,
      mode: "create",
      queryParams: {
        merchantStatus: "",
      },
      apiMerchantDetail,
      ruleForm: {},
      formOptions: [
        {
          type: "select",
          field: "stockLibraryCode",
          title: "合作商类型",
          disabled: true,
          default: "1",
          placeholder: "请选择...",
          options: [{ value: "1", label: "发包商" }],
          rules: [
            { required: true, message: "请选择合作商类型", trigger: "change" },
          ],
        },

        {
          type: "input",
          field: "merchantName",
          default: "123",

          title: "商家名称",
          default: "",
          placeholder: "商家名称...",
          maxlength: 20,
          showWordLimit: true,
          rules: [
            { required: true, message: "请输入商家名称...", trigger: "blur" },
            {
              trigger: "blur",
              validator: validateRealName,
            },
          ],
        },
        {
          type: "input",
          field: "merchantContactName",
          title: "联系人姓名",
          default: "",
          maxlength: 30,
          placeholder: "联系人姓名...",
          rules: [
            { required: true, message: "请输入联系人姓名...", trigger: "blur" },
            {
              trigger: "blur",
              validator: validateRealName,
            },
          ],
        },
        {
          type: "input",
          field: "merchantContactPhoneNumber",
          title: "联系人手机号",
          default: "",
          maxlength: 11,
          placeholder: "联系人手机号...",
          rules: [
            {
              required: true,
              message: "请输入联系人手机号...",
              trigger: "blur",
            },
            {
              trigger: "change",
              validator: validatePhone,
            },
          ],
        },
        {
          type: "input",
          field: "merchantAccount",
          title: "超级管理员账号",
          default: "",
          maxlength: 11,
          placeholder: "请输入手机号...",
          slot: "adminUserName",
          rules: [
            {
              required: true,
              message: "请输入手机号...",
              trigger: "blur",
            },
            {
              trigger: "change",
              validator: validatePhone,
              trigger: "blur",
            },
          ],
        },
        {
          type: "textarea",
          field: "remark",
          title: "备注",
          default: "",
          maxlength: 40,
          placeholder: "备注...",
        },
      ],
      tableOption: [
        {
          label: "商家信息",
          prop: "info",
          width: 150,
          render(createElement, { row }) {
            const dom = (
              <div class="row">
                <div>商家id:{row.merchantId}</div>
                <div>名称:{row.merchantName}</div>
                <div>超管账号:{row.merchantAccount}</div>
              </div>
            );
            return dom;
          },
        },
        {
          label: "合作联系人",
          prop: "partner",
          width: 150,
          render(createElement, { row }) {
            const dom = (
              <div class="row">
                <div>{row.merchantContactName}</div>
                <div>{row.merchantContactPhoneNumber}</div>
              </div>
            );
            return dom;
          },
        },
        {
          label: "资金",
          prop: "money",
          width: 150,
          render(createElement, { row }) {
            const dom = (
              <div class="row">
                <div>
                  可用金额:
                  {Number(row.availableBalance).tranFormat(2, -2, true)}
                </div>
                <div>
                  累计充值:
                  {Number(row.accumulatedRecharge).tranFormat(2, -2, true)}
                </div>
              </div>
            );
            return dom;
          },
        },

        {
          label: "状态",
          prop: "merchantStatus",
          width: 70,
          render(h, { row }) {
            return (
              <el-link
                type={row.merchantStatus == "YES" ? "success" : "danger"}
              >
                {filterMerchantStatusEnum(row.merchantStatus)}
              </el-link>
            );
          },
        },
        {
          label: "备注",
          prop: "remark",
          width: 120,
        },
        {
          label: "创建时间",
          width: 80,
          prop: "createTim5e",
          render(createElement, { row }) {
            try {
              const strArr = row.createTime.split(" ");
              const dom = (
                <div class="row">
                  <div>{strArr[0]}</div>
                  <div>{strArr[1]}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          },
        },

        {
          label: "操作",
          width: 100,
          prop: "operate",
          fixed: "right",
          render(h, { row }) {
            return h("div", [
              h("el-link", {
                domProps: {
                  innerHTML: "编辑",
                },
                class: ["mr10"],
                props: {
                  type: "warning",
                },
                on: {
                  click() {
                    _this.mode = "edit";
                    _this.$nextTick(() => {
                      _this.ruleForm.merchantId = row.merchantId;
                      _this.$refs.theFormCreate.open({
                        merchantId: row.merchantId,
                      });
                    });
                  },
                },
              }),
              h("el-link", {
                domProps: {
                  innerHTML: row.merchantStatus == "NO" ? "开启" : "停用",
                },
                class: ["mr10"],
                props: {
                  type: row.merchantStatus == "NO" ? "success" : "danger",
                },
                on: {
                  click() {
                    _this
                      .$confirm(
                        `此操作将${
                          row.merchantStatus == "YES" ? "停用" : "开启"
                        }发包商, 是否继续?`,
                        "提示",
                        {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning",
                        }
                      )
                      .then(() => {
                        apiMerchantUpdateStatus({
                          merchantId: row.merchantId,
                          merchantStatus:
                            row.merchantStatus == "YES" ? "NO" : "YES",
                        }).then((res) => {
                          row.merchantStatus =
                            row.merchantStatus == "YES" ? "NO" : "YES";
                          _this.$message({
                            type: "success",
                            message: "操作成功!",
                          });
                        });
                      })
                      .catch(() => {});
                  },
                },
              }),
              h("el-link", {
                domProps: {
                  innerHTML: "充值",
                },
                props: {
                  type: "primary",
                },
                on: {
                  click() {
                    _this.$router.push({
                      path: "/financeManager/outSourceRecharge/recharge",
                      query: {},
                    });
                  },
                },
              }),
            ]);
          },
        },
      ],
    };
  },
  mounted() {},
  methods: {
    handleSubmit(values) {
      const params = {
        merchantName: values.merchantName,
        merchantContactName: values.merchantContactName,
        merchantContactPhoneNumber: values.merchantContactPhoneNumber,
        merchantAccount: values.merchantAccount,
        remark: values.remark,
      };
      if (this.mode == "edit") {
        params.merchantId = values.merchantId;
        apiMerchantUpdate(params).then((res) => {
          this.$message({
            type: "success",
            message: "编辑发包商成功",
          });
          this.$refs.tableRefs.refresh();
        });
      } else {
        apiMerchantCreate(params).then((res) => {
          this.$message({
            type: "success",
            message: "新建发包商成功",
          });
          this.$refs.tableRefs.refresh();
        });
      }
    },
    // 编辑发包商时，修改手机号
    handleEditMobile() {
      this.$confirm(
        "改绑超级管理员账号，会造成原账号无法登录，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "继续改绑",
          cancelButtonText: "返回",
          type: "warning",
        }
      )
        .then(() => {
          this.$prompt("", "请输入新手机号", {
            confirmButtonText: "确认",
            inputPattern: /^[1][3-9][0-9]{9}$/,
            inputErrorMessage: "手机号格式错误",
            showCancelButton: false,
          })
            .then(({ value }) => {
              this.$set(this.ruleForm,'merchantAccount',value)
            })
            .catch(() => {});
        })
        .catch(() => {});
    },

    // 新建师傅
    handleCreate() {
      this.mode = "create";
      this.$nextTick(() => {
        this.ruleForm.merchantId = "";
        this.$refs.theFormCreate.open();
      });
    },
    // 导出
    async handleExport() {
      this.exportLoading = true;
      const res = await apiContractInfoPage({
        pageNo: 1,
        pageSize: -1,
        ...this.queryParams,
      });
      if (res.code === 200) {
        let header = [
          {
            title: "借条ID",
            prop: "contractId",
            valueType: "s",
          },
          {
            title: "借条状态",
            prop: "contractState",
            valueType: "s",
          },
          {
            title: "出借人or借款人发起",
            prop: "promoterType",
            valueType: "s",
          },
          {
            title: "出借人姓名",
            prop: "creditorMemberName",
            valueType: "s",
          },
          {
            title: "出借人手机号",
            prop: "creditorMemberPhone",
            valueType: "s",
          },
          {
            title: "出借人身份证号",
            prop: "creditorMemberIdNumber",
            valueType: "s",
          },
          { title: "借款人姓名", prop: "debtorMemberName", valueType: "s" },
          {
            title: "借款人手机号",
            prop: "debtorMemberPhone",
            valueType: "s",
          },
          {
            title: "借款人身份证号",
            prop: "debtorMemberIdNumber",
            valueType: "s",
          },

          {
            title: "借款金额",
            prop: "loanAmount",
            valueType: "n",
            numFmt: $numFmt.money,
          },
          {
            title: "借款期间",
            prop: "timeRange", //debtorTime  repaymentTime
            valueType: "s",
          },
          {
            title: "借款事由",
            prop: "borrowingReason",
          },
          {
            title: "利息",
            prop: "contractInterest",
            valueType: "n",
            numFmt: $numFmt.money,
          },
          {
            title: "年利率",
            prop: "interestAnnualizedPercentage",
            valueType: "n",
            numFmt: $numFmt.ratio,
          },
          {
            title: "逾期利率",
            prop: "timeInterest",
            valueType: "n",
            numFmt: $numFmt.ratio,
          },
          {
            title: "备注说明",
            prop: "contractRemarks",
            valueType: "s",
            width: 100,
          },
          {
            title: "支付方式",
            prop: "paymentType",
            valueType: "s",
          },
          {
            title: "支付宝转账需要支付宝流水号",
            prop: "tradeNo",
            valueType: "s",
          },
          { title: "管辖法院", prop: "courtAddress", valueType: "s" },

          {
            title: "借款人地址",
            prop: "debtorMemberAddress",
            valueType: "s",
          },
          {
            title: "创建人签鸽用户id",
            prop: "createMemberId",
            valueType: "s",
          },

          { title: "创建人支付宝id", prop: "alipayOpenId", valueType: "s" },
          { title: "创建人昵称", prop: "alipayNickName", valueType: "s" },
          { title: "创建人手机号", prop: "createPhone", valueType: "s" },
          { title: "合同支付时间", prop: "contractPayTime", valueType: "s" },
          { title: "填写中时间", prop: "createTime", valueType: "s" },
          { title: "签署中时间", prop: "fillTime", valueType: "s" },
          { title: "已生效时间", prop: "effectiveTime", valueType: "s" },
          { title: "已撤回时间", prop: "withdrawalTime", valueType: "s" },
          { title: "已拒签时间", prop: "refusalTime", valueType: "s" },
          { title: "已失效时间", prop: "expirationTime", valueType: "s" },
        ];

        let dataSource = res.data.records.map((item) => {
          return {};
        });
        const option = {
          dataSource: dataSource,
          header: header,
          fileName: "入驻审核" + this.getStatusTxt(),
        };
        window.$Json2Excel(option);
        this.exportLoading = false;
      } else {
        this.$message({
          message: "导出操作失败,请重试",
          type: "warring",
        });
        this.exportLoading = false;
      }
    },
    getStatusTxt() {
      if (this.activeStatus === "all") {
        return "";
      } else if (this.activeStatus === "wait") {
        return "待审核";
      } else if (this.activeStatus === "pass") {
        return "审核通过";
      } else if (this.activeStatus === "refuse") {
        return "审核拒绝";
      }
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .row {
  .span4 {
    flex: 1;
  }
  .span20 {
    flex: 5;
  }
}
</style>
